import Vue,{VNode,PropType,PropOptions} from 'vue';
import {VueConstructor} from 'vue/types/vue';
import {PlainObject} from '../../../../types';
import Icon from '../icon';
/**
 * 定义非响应数据
 * @property {*} interval 时间轮询
 */
export interface NoticeVue extends Vue{
	interval:any,
}
/**
 * 轻提示类型
 */
export type NoticeType='info'|'success'|'warning'|'error';
/**
 * 显示位置
 */
export type Position='left'|'center'|'right';
/**
 * 关闭时调用的函数
 */
export interface CloseFunction{
	():void,
}
const defaultDuration=3;
//todo title和content需要支持自定义渲染
/**
 * 轻提示
 * @author 唐国雄
 * @date 2021/7/6
 * 属性----------------------
 * :title			标题, string
 * :content			内容, string
 * :type			轻提示类型, NoticeType
 * :width			宽度, number
 * :duration		显示时长, 0表示不限制, number
 * :on-close		关闭时的回调, CloseFunction
 * :closeable		是否有关闭按钮, boolean
 */
export default (Vue as VueConstructor<NoticeVue>).extend({
	name:'Notice',
	props:{
		//标题
		title:{
			type:String,
			required:true,
		},
		//内容
		content:String,
		//轻提示类型
		type:{
			type:String,
			default:'info',
			validator(v){
				return [
					'info',
					'success',
					'warning',
					'error',
				].indexOf(v)!==-1;
			}
		} as PropOptions<NoticeType>,
		//宽度
		width:{
			type:Number,
			default:320
		},
		//显示时长
		duration:{
			type:Number,
			default:defaultDuration,
			validator(v){
				return v>=0;
			}
		},
		//关闭时的回调
		onClose:Function as PropType<CloseFunction>,
		//是否有关闭按钮
		closeable:{
			type:Boolean,
			default:true,
		}
	},
	computed:{
		classes():string{
			return 'lexmis-Notice'+
				` lexmis--${this.type}`+
				(this.noBody?' lexmis--noBody':' lexmis--hasBody')+
				(this.closeable?'':' lexmis--noClose');
		},
		//图标属性
		iconProps():PlainObject{
			switch(this.type){
				case 'info':
					return {
						name:'info',
					};
				case 'success':
					return {
						name:'check_circle',
					};
				case 'warning':
					return {
						name:'error',
					};
				case 'error':
					return {
						name:'cancel',
					};
				default:
					return {
					};
			}
		},
		//是否有内容
		noBody():boolean{
			return !this.content;
		},
	},
	mounted(){
		const duration=this.duration;
		if(duration>0){
			const timeout=setTimeout(() => {
				this.onClose();
			},duration*1000);
			this.$once('hook:beforeDestroy',function(){
				clearTimeout(timeout);
			});
		}
	},
	render(h):VNode{
		return h('div',{
			staticClass:this.classes,
			staticStyle:{
				width:this.width+'px',
			}
		},[
			h('div',{
				staticClass:'lexmis_head',
			},[
				h(Icon,{
					staticClass:'lexmis_type',
					props:this.iconProps,
				}),
				h('div',{
					staticClass:'lexmis_title',
				},this.title),
				this.closeable
					?h(Icon,{
						staticClass:'lexmis_close',
						props:{
							name:'close',
						},
						on:{
							click:() => {
								this.onClose();
							}
						}
					})
					:null
			]),
			this.noBody
				?null
				:h('div',{
					staticClass:'lexmis_body',
				},this.content),
		]);
	}
});
